<template>
  <div class="coupon-consume-main">
    <!-- 页面标题 -->
    <!-- <div class="page-header">
      <h2>优惠券核销管理</h2>
      <p class="page-description">管理和查看优惠券核销操作，支持验证、核销、记录查询和数据统计</p>
    </div> -->

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <i class="el-icon-tickets"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statsData.total || 0 }}</div>
                <div class="stat-label">总优惠券数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon available">
                <i class="el-icon-check"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statsData.available || 0 }}</div>
                <div class="stat-label">可用优惠券</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon distributed">
                <i class="el-icon-share"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statsData.distributed || 0 }}</div>
                <div class="stat-label">已分发</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon rate">
                <i class="el-icon-pie-chart"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statsData.distribution_rate || 0 }}%</div>
                <div class="stat-label">分发率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 快速操作 -->
    <el-row :gutter="20" class="quick-actions">
      <el-col :span="8">
        <el-card class="action-card" @click.native="navigateTo('/nfc/coupon/verify')">
          <div class="action-content">
            <div class="action-icon-wrapper">
              <i class="el-icon-search action-icon"></i>
            </div>
            <div class="action-text">
              <h3>验证优惠券</h3>
              <p>验证优惠券是否可以核销</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="action-card" @click.native="navigateToConsume()">
          <div class="action-content">
            <div class="action-icon-wrapper">
              <i class="el-icon-check action-icon"></i>
            </div>
            <div class="action-text">
              <h3>核销优惠券</h3>
              <p>执行优惠券核销操作</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="action-card" @click.native="navigateTo('/nfc/coupon/records')">
          <div class="action-content">
            <div class="action-icon-wrapper">
              <i class="el-icon-document action-icon"></i>
            </div>
            <div class="action-text">
              <h3>核销记录</h3>
              <p>查看历史核销记录</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 核销趋势图表 -->
    <el-card class="chart-card">
      <div slot="header" class="clearfix">
        <span>核销趋势</span>
        <div style="float: right;">
          <el-radio-group v-model="chartPeriod" size="small" @change="loadTrendData">
            <el-radio-button label="7">最近7天</el-radio-button>
            <el-radio-button label="30">最近30天</el-radio-button>
            <el-radio-button label="90">最近90天</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div id="trendChart" style="height: 300px;"></div>
    </el-card>

    <!-- 最近核销记录 -->
    <el-card class="recent-records">
      <div slot="header" class="clearfix">
        <span>最近核销记录</span>
        <el-button 
          style="float: right;" 
          type="text" 
          @click="navigateTo('/nfc/coupon/records')"
        >
          查看全部
        </el-button>
      </div>
      <el-table :data="recentRecords" style="width: 100%">
        <el-table-column prop="coupon_code" label="优惠券代码" width="150"></el-table-column>
        <el-table-column prop="coupon_name" label="优惠券名称" width="200"></el-table-column>
        <el-table-column prop="consume_amount" label="消费金额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.consume_amount || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="consume_time" label="核销时间" width="180"></el-table-column>
        <el-table-column prop="operated_by_merchant_staff" label="操作员工" width="120"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="viewRecord(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getConsumeStats, getConsumeTrend, getConsumeRecords } from '@/api/nfc'

export default {
  name: 'CouponConsumeIndex',
  data() {
    return {
      statsData: {
        total: 0,
        available: 0,
        distributed: 0,
        distribution_rate: 0,
        consumed: 0,
        pending: 0,
        consume_rate: 0,
        total_amount: 0
      },
      chartPeriod: '7',
      trendChart: null,
      recentRecords: [],
      loading: false
    }
  },
  mounted() {
    this.loadStatsData()
    this.loadTrendData()
    this.loadRecentRecords()
    this.initChart()
  },
  beforeDestroy() {
    if (this.trendChart) {
      this.trendChart.dispose()
    }
  },
  methods: {
    /**
     * 加载统计数据
     */
    async loadStatsData() {
      try {
        const response = await getConsumeStats({
          merchant_id: this.getCurrentMerchantId()
        })
        if (response.code === 200) {
          this.statsData = response.data.coupon_stats || {}
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
        this.$message.error('加载统计数据失败')
      }
    },

    /**
     * 加载趋势数据
     */
    async loadTrendData() {
      try {
        const endDate = new Date()
        const startDate = new Date()
        startDate.setDate(endDate.getDate() - parseInt(this.chartPeriod))

        const response = await getConsumeTrend({
          merchant_id: this.getCurrentMerchantId(),
          start_date: this.formatDate(startDate),
          end_date: this.formatDate(endDate),
          group_by: 'day'
        })

        if (response.code === 200) {
          this.updateChart(response.data.trend || [])
        }
      } catch (error) {
        console.error('加载趋势数据失败:', error)
      }
    },

    /**
     * 加载最近核销记录
     */
    async loadRecentRecords() {
      try {
        const response = await getConsumeRecords({
          merchant_id: this.getCurrentMerchantId(),
          page: 1,
          limit: 5
        })
        if (response.code === 200) {
          this.recentRecords = response.data.records || []
        }
      } catch (error) {
        console.error('加载最近记录失败:', error)
      }
    },

    /**
     * 初始化图表
     */
    initChart() {
      this.$nextTick(() => {
        const chartDom = document.getElementById('trendChart')
        if (chartDom) {
          this.trendChart = echarts.init(chartDom)
        }
      })
    },

    /**
     * 更新图表数据
     */
    updateChart(data) {
      if (!this.trendChart) return

      const dates = data.map(item => item.date)
      const counts = data.map(item => item.count)
      const amounts = data.map(item => item.amount)

      const option = {
        title: {
          text: '核销趋势',
          left: 'center',
          textStyle: {
            fontSize: 14,
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].axisValue + '<br/>'
            params.forEach(param => {
              if (param.seriesName === '核销数量') {
                result += param.marker + param.seriesName + ': ' + param.value + '张<br/>'
              } else {
                result += param.marker + param.seriesName + ': ¥' + param.value + '<br/>'
              }
            })
            return result
          }
        },
        legend: {
          data: ['核销数量', '核销金额'],
          bottom: 10
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '数量(张)',
            position: 'left'
          },
          {
            type: 'value',
            name: '金额(元)',
            position: 'right'
          }
        ],
        series: [
          {
            name: '核销数量',
            type: 'line',
            data: counts,
            smooth: true,
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '核销金额',
            type: 'bar',
            yAxisIndex: 1,
            data: amounts,
            itemStyle: {
              color: '#67C23A'
            }
          }
        ]
      }

      this.trendChart.setOption(option)
    },

    /**
     * 导航到指定页面
     */
    navigateTo(path) {
      this.$router.push(path)
    },

    /**
     * 跳转到核销操作页面
     */
    navigateToConsume() {
      // 跳转到验证页面，验证后可以直接核销
      this.$router.push('/nfc/coupon/verify')
    },

    /**
     * 查看记录详情
     */
    viewRecord(record) {
      this.$router.push({
        path: '/nfc/coupon/records',
        query: { id: record.id }
      })
    },

    /**
     * 获取当前商户ID
     */
    getCurrentMerchantId() {
      // 这里应该从用户信息或全局状态获取
      return this.$store.state.user.merchantId || 1
    },

    /**
     * 格式化日期
     */
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style scoped>
.coupon-consume-main {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 500;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.statistics-cards {
  margin-bottom: 30px;
}

.stat-card {
  position: relative;
  overflow: hidden;
  height: 120px;
}

.stat-card .el-card__body {
  padding: 20px;
  height: 100%;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: #fff;
}

.stat-info {
  flex: 1;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.available {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.distributed {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.rate {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.quick-actions {
  margin-bottom: 30px;
}

.action-card {
  cursor: pointer;
  transition: all 0.3s;
  height: 140px;
}

.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-card .el-card__body {
  padding: 20px;
  height: 100%;
}

.action-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
}

.action-icon-wrapper {
  margin-bottom: 15px;
}

.action-icon {
  font-size: 36px;
  color: #409EFF;
}

.action-text {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.action-text h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
  line-height: 1.2;
}

.action-text p {
  margin: 0;
  color: #909399;
  font-size: 13px;
  line-height: 1.4;
}

.chart-card {
  margin-bottom: 30px;
}

.recent-records {
  margin-bottom: 30px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards .el-col {
    margin-bottom: 15px;
  }
  
  .quick-actions .el-col {
    margin-bottom: 15px;
  }
  
  .stats-number {
    font-size: 24px;
  }
  
  .action-icon {
    font-size: 28px;
  }
}</style> 